package mk.jug.academy.controller;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.images.Image;
import com.google.appengine.api.images.ImagesService;
import com.google.appengine.api.images.ImagesServiceFactory;
import com.google.appengine.api.images.Transform;

/**
 * View layer coordinator for the serving and management of stored resources.
 *
 * @author Ice.Penov
 */
@Controller
public class ResourceController {
	
	private static final Logger LOG = Logger.getLogger(ResourceController.class.getName());	
	private BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
	
	@RequestMapping(value = "/serve.do", method = RequestMethod.GET)
	public void serve(HttpServletResponse response, @RequestParam(value = "key") String key) {
		try {
			blobstoreService.serve(new BlobKey(key), response);
		} catch (IOException e) {
			LOG.log(Level.SEVERE, "Error while serving resource", e);
		}
	}
	
	@RequestMapping(value = "/resize.do", method = RequestMethod.GET)
	public void resize(HttpServletResponse response, @RequestParam("key") String key, @RequestParam("width") Integer width, @RequestParam("height") Integer height) throws IOException {
		ImagesService imageService = ImagesServiceFactory.getImagesService();
		Image oldImage = ImagesServiceFactory.makeImageFromBlob(new BlobKey(key));
		Transform resize = ImagesServiceFactory.makeResize(125, 125);
		Image newImage = imageService.applyTransform(resize, oldImage);
		response.getOutputStream().write(newImage.getImageData());		
	}

}
